<?php

declare(strict_types=1);

namespace app\api\controller\ucenter;

use app\api\controller\Api;
use app\common\system\logic\DepartmentLogic;
use app\common\system\logic\UserDepartmentLogic;
use app\common\system\logic\UserLogic;
use app\common\system\logic\UserRoleLogic;
use app\common\system\model\AuthRole;
use think\db\exception\DbException;
use think\facade\Db;
use util\Format;

class User extends Api
{
    // 用户列表
    public function index()
    {
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['nickname|realname|mobile', 'like', "%{$post['keyword']}%"];
        $model = new \app\common\system\model\User();

        if (isset($post['status']) && $post['status'] != '') {
            $where[] = ['status', '=', $post['status']];
        }

        if (!empty($post['role_id'])) {
            $roleId = $post['role_id'];
            $model = $model->whereIn('id', function ($query) use ($roleId) {
                $query->table('tk_system_user_role')->where('role_id', $roleId)->where('delete_time', 0)->field('user_id');
            });
        }

        if (isset($post['department_id']) && $post['department_id'] > 0) {
            $dptId = $post['department_id'];
            $model = $model->whereIn('id', function ($query) use ($dptId) {
                $query->table('tk_system_user_department')->where('department_id', $dptId)->where('delete_time', 0)->field('user_id');
            });
        }

        list($cfg) = Format::pagination($post);
        $model = $model->where($where);
        $pg = $model->where($where)->paginate($cfg);
        $rows = $pg->getCollection();

        $userRoleLogic = new UserRoleLogic();
        foreach ($rows as &$row) {
            $row['role'] = $userRoleLogic->getUserRole($row->id, false);
            $row['dpt'] =  $userRoleLogic->getUserDpt($row->id, false);
        }

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    public function picker()
    {
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['nickname|realname|mobile', 'like', "%{$post['keyword']}%"];
        $model = new \app\common\system\model\User();

        $where[] = ['status', '=', 1];
        $model = $model->where($where);
        $rows = $model->field("id,realname")->where($where)->limit(10)->select();
        

        return success($rows, '获取数据成功');
    }

    public function getAllUser()
    {
        $userModel = new \app\common\system\model\User();
        $result['userList'] = $userModel->where('status', 1)->field('id,realname')->select();

        $roleModel = new AuthRole();
        $result['roleList'] = $roleModel->where('is_valid', 1)->select();

        return success($result);
    }

    // 添加用户
    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        $validate = new \app\common\system\validate\UserValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new \app\common\system\model\User();
        $post['password'] = md5($post['password']);
        $result = $model->save($post);

        $user = $this->request->user;
        if ($result) {
            $userId = $model->id;
            if (isset($post['department'])) {
                $dptLogic = new \app\common\system\logic\DepartmentLogic();
                $dptLogic->createUserDepartment($userId, $user['id'], $post['department']);
            }


            return success([], '添加用户成功');
        } else {
            return error([], '添加用户失败');
        }
    }

    public function read()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], "参数错误");

        $userModel = new \app\common\system\model\User();
        $user = $userModel->withoutField('password')->where('id', $post['id'])->find();
        if (empty($user)) return error([], "用户已不存在");

        $userDepartmentLogic = new UserDepartmentLogic();
        $user['department'] = $userDepartmentLogic->getUserDepartment($post['id']);
        $data['user'] = $user;

        return success($data, '获取员工信息成功');
    }

    // 保存用户
    public function save()
    {
        $post = $this->request->post();

        $validate = new \app\common\system\validate\UserValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new \app\common\system\model\User();
        $row = $model->where('id', $post['id'])->find();
        if (!empty($post['password'])) {
            $post['password'] = md5($post['password']);
        } else {
            unset($post['password']);
        }

        $user = $this->request->user;
        try {
            $row->save($post);
            if (isset($post['department'])) {
                // 更新用户的部门信息
                $dptLogic = new \app\common\system\logic\DepartmentLogic();
                $dptLogic->updateUserDepartment($post['id'], $user['id'], $post['department']);
            }
            // 更新用户的缓存
            $userLogic = new UserLogic();
            $userLogic->resetUserCache($post['id']);

        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        return success([], '编辑用户信息成功');
    }

    public function bindWechat()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], "缺少id参数");

        $userModel = new \app\common\system\model\User();
        $user = $userModel->where('id', $post['id'])->find();
        if (empty($user)) return error([], "用户不存在");
        if (empty($user['mobile'])) return error([], "用户未绑定手机号");

        $wechatLogic = new \app\common\third\Wechat();
        $result = $wechatLogic->get_user_id($user['mobile']);

        if ($result['errcode'] == 0) {
            $user->save(['work_wechat' => $result['userid']]);
            // 重置用户的缓存
            $userLogic = new UserLogic();
            $userLogic->resetUserCache($user['id']);
            return success([], '绑定成功');
        } else {
            return error([], $result['errmsg'], $result['errcode']);
        }
    }

    // 修改头像
    public function avatar()
    {
        $post = $this->request->post();
        $reqUser = $this->request->user;
        $dir = !empty($post['field']) ? $post['field'] : 'file';
        // 获取上传配置
        $systemConfigLogic = new \app\common\config\logic\ConfigSystem();
        $uploadConfig = $systemConfigLogic->getConfigItem("upload");

        $file = $this->request->file('file');
        if (empty($file)) return error([], '请选择要上传的文件');

        try {
            $rules = [
                "file" => ["fileSize:{$uploadConfig['size']}", "fileExt:{$uploadConfig['ext']}"],
            ];
            $messages = [
                "file.fileSize" => '文件不超过',
                "file.fileExt"  => '不支持的文件格式'
            ];
            $validateLogic = validate($rules, $messages);
            $checkRs = $validateLogic->check(['file' => $file]);
            if (!$checkRs) {
                return error([], $validateLogic->getError());
            }

            // 上传到本地服务器
            $env = getenv("SERVER_ENV");
            if ($env == 'test') {
                $index = "public";
            } else {
                $index = "image";
            }

            $saveName = \think\facade\Filesystem::disk($index)->putFile($dir, $file);
            if ($saveName) {
                $config = config('filesystem.disks');
                $saveName = $config[$index]['url'] . '/' . str_ireplace('\\', '/', $saveName);
                $result['path'] = $this->request->domain() . $saveName;

                $model = new \app\common\system\model\User();
                $user = $model->where('id', $reqUser['id'])->find();
                $user->save(['avatar' => $result['path']]);

                $userLogic = new UserLogic();
                $userLogic->resetUserCache($reqUser['id']);

                return success($result, '上传成功');
            } else {
                return error([], '上传失败');
            }
        } catch (ValidateException $e) {
            return error([], $e->getMessage());
        }
    }


    // 修改密码
    public function password()
    {
        $post = $this->request->post();

        $validate = new \app\common\system\validate\PasswordValidate();
        if (!$validate->check($post)) {
            return error([], $validate->getError());
        }

        $model = new \app\common\system\model\User();
        $user = $model->where('id', $this->request->user['id'])->find();
        if ($user['password'] != md5($post['oldpassword'])) return error([], '原始密码错误');
        $result = $user->save(['password' => md5($post['newpassword'])]);

        if ($result) {
            return success([], '修改密码成功');
        } else {
            return error([], '修改密码失败');
        }
    }

    public function info()
    {
        $user = $this->request->user;

        $userLogic = new UserLogic();
        $result['user'] = $userLogic->getUser($user['id']);

        $userRoleLogic = new UserRoleLogic();
        $result['rules'] = $userRoleLogic->getUserFuncItems($user['id']);

        return success($result, '获取数据成功');
    }

    // 微信小程序端更新用户信息
    public function updateInfo()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        
        $model = new \app\common\system\model\User();
        $userInfo = $model->where('id', $user['id'])->find();
        
        $data = [];
        $data['realname'] = $post['realname'];
        $data['nickname'] = $post['nickname'];
        $data['mobile'] = $post['mobile'];
        $data['email'] = $post['email'];
        $data['avatar'] = $post['avatar'];

        // 构建验证器
        $validate = new \app\common\system\validate\UserValidate();
        if (!$validate->scene('update_info')->check($data)) {
            return error([], $validate->getError());
        }

        if (!empty($post['password'])) {
            $data['password'] = md5($post['password']);
            if ($userInfo['password'] != $data['password']) {
                return error([], '原始密码错误');
            }

            unset($data['password']);
            if (!empty($post['new_password'])) {
                $data['password'] = md5($post['new_password']);
            }
        }
        
        $result = $model->where('id', $user['id'])->save($data);
        if ($result) {
            return success([], '更新用户信息成功');
        } else {
            return error([], '更新用户信息失败');
        }
    }

    // 查询部门下所有的员工
    public function getDepartmentUsers()
    {
        $user = $this->request->user;
        // 获取所有的
        $dptLogic = new DepartmentLogic();
        $dptIds = $dptLogic->getUserDptIds($user['id']);

        $hasWhere = [];
        $hasWhere[] = ['department_id', 'in', $dptIds];

        $result = [];
        $users = \app\common\system\model\User::hasWhere('department', $hasWhere)->visible(['id', 'realname', 'nickname'])->select();
        $result['userList'] = $users;

        return success($result);
    }

    public function leave()
    {
    }
}
